package com.atguigu.lease.web.app.service.impl;


import com.atguigu.lease.common.Advice.LeaseException;
import com.atguigu.lease.common.constants.RedisConstant;
import com.atguigu.lease.common.jwt.JwtUtil;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.model.entity.UserInfo;
import com.atguigu.lease.model.enums.BaseStatus;
import com.atguigu.lease.web.app.service.LoginService;
import com.atguigu.lease.web.app.service.UserInfoService;
import com.atguigu.lease.web.app.vo.user.LoginVo;
import com.atguigu.lease.web.app.vo.user.UserInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;
    @Autowired
    private UserInfoService userInfoService;


    @Override
    public void getCodeByPhone(String phone) {
    //将电话号码作为Key
     String  key = RedisConstant.APP_LOGIN_PREFIX+ phone;
     //判断有没有这个Key
        Boolean b = redisTemplate.hasKey(key);
        if( b){
            Long expire = redisTemplate.getExpire(key, TimeUnit.SECONDS);//获取这个key的剩余时间
            Integer appLoginCodeTtlSec = RedisConstant.APP_LOGIN_CODE_TTL_SEC;//获取验证码的过期时间
            Integer appLoginCodeResendTimeSec = RedisConstant.APP_LOGIN_CODE_RESEND_TIME_SEC;//获取重新发送验证码的间隔时间
            if (appLoginCodeTtlSec-expire<appLoginCodeResendTimeSec)//判断剩余时间是否小于间隔时间
            {
                throw new LeaseException(ResultCodeEnum.APP_SEND_SMS_TOO_OFTEN);
            }
        }
        StringBuilder stringBuilder = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < 6; i++) {
            stringBuilder.append(random.nextInt(10));//随机生成一个数字
        }
        String string = stringBuilder.toString();//验证码
        System.out.println("验证码为:"+ string);
        redisTemplate.opsForValue().set(key,string,RedisConstant.APP_LOGIN_CODE_TTL_SEC,TimeUnit.SECONDS);
    }

    @Override
    public String login(LoginVo loginVo) {
        String key = RedisConstant.APP_LOGIN_PREFIX+ loginVo.getPhone();//获取验证码的key
        String code = (String) redisTemplate.opsForValue().get(key);//获取验证码
        if (code==null||!code.equals(loginVo.getCode()))//判断验证码是否一致
        {
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_ERROR);
        }
        LambdaQueryWrapper<UserInfo> queryWrapper = new LambdaQueryWrapper<>();//查询用户
        queryWrapper.eq(UserInfo::getPhone, loginVo.getPhone());//查询手机号
        UserInfo one = userInfoService.getOne(queryWrapper);
        if (one==null){
            UserInfo userInfo = new UserInfo();//创建用户
            userInfo.setStatus(BaseStatus.ENABLE);//设置状态
            userInfo.setPhone(loginVo.getPhone());//设置手机号
            userInfo.setAvatarUrl("http://www.baidu.com/img/bd_logo.png");//设置头像
            userInfo.setNickname("用户"+loginVo.getPhone());//设置昵称
            userInfoService.save(userInfo);
            one = userInfo;
        }
        if (one.getStatus()==BaseStatus.DISABLE)//判断用户状态
        {
            throw new LeaseException(ResultCodeEnum.APP_ACCOUNT_DISABLED_ERROR);
        }
        String token = JwtUtil.createToken(one.getId(), one.getPhone());//生成token
        return token;
    }

    @Override
    public UserInfoVo systemUserInfo(String accToken) {
        Claims claims = JwtUtil.parseToken(accToken);//解析token
        Integer userId= (Integer) claims.get("userId");//获取用户id
        UserInfo userInfo = userInfoService.getById(userId);//获取用户信息
        UserInfoVo userInfoVo = new UserInfoVo(userInfo.getNickname(), userInfo.getAvatarUrl());//创建用户信息对象并且将用户的昵称和头像赋给对象
        return userInfoVo;
    }


}
